# -*- coding: utf-8 -*-
import os
import Models
import MasterPage
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    
    def get(self):
        user = GetUser(self)
        
        url = ""
        
        geopts = db.GqlQuery("SELECT * FROM GLatLngModel WHERE author = :author", author=user)
        for geopt in geopts:
            url += str(geopt.geopt)  + "|"

	Display(self,user,url)
	
    def post(self):
        user = GetUser(self)
            
        action = self.request.POST.get('actiontype')

        if (action == 'Save your route'):
            
            #try to delete items first
            q = db.GqlQuery("SELECT * FROM GLatLngModel WHERE author = :author", author=user)
            results = q.fetch(100)
            for res in results:
                res.delete()

            #add items
            postpoints = self.request.POST.get('points')
            #self.response.out.write("Points:" + postpoints);
            points = postpoints.split("|")
            for i in range(len(points)-1):
                xy = points[i].split(",")
                latlng = Models.GLatLngModel()
                #self.response.out.write("Points:" + xy[0]);
                latlng.author = user
                geopt = db.GeoPt(xy[0],xy[1])
                latlng.geopt = geopt
                latlng.put()
                
        url = ""
        
        geopts = db.GqlQuery("SELECT * FROM GLatLngModel WHERE author = :author", author=user)
        for geopt in geopts:
            url += str(geopt.geopt)  + "|"
	
        Display(self,user,url)
        
application = webapp.WSGIApplication([('/route', MainPage)],debug=True)

def GetUser(self):
    user = users.get_current_user()
    if user:
        self.response.headers['Content-Type'] = 'text/html'
    else:
        self.redirect(users.create_login_url(self.request.uri))
    return user

def Display(self,user,url):
    header = MasterPage.OutputHeader(user)
    footer = MasterPage.OutputFooter()
            
    template_values = {'header': header, 'footer': footer, 'nickname': user.nickname(),'url': url}

    path = os.path.join(os.path.dirname(__file__), 'html/Route.html')
    self.response.out.write(template.render(path, template_values))
        
def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()
